<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 6/10/21
 * Time: 3:01 PM
 */

namespace app\api\controller\v1;

use app\api\model\UserTiMoneyOrder;

use app\api\model\User as UserModel;
use app\api\model\UserMoney as UserMoneyModel;
use app\api\model\StoreUser as StoreUserModel;
use app\api\model\TeamUser as TeamUserModel;
use think\facade\Log;

class PayMoney
{
    /**
     * 1. 判断用户信息
     * 2. 判断提现信息
     * 3. 进行提现操作
     * 4. 成功返现
     */
    private $user;


    private $order;

    // 企业付款到余额
    public function addUserMoney($order_no)
    {
        Log::init([
            'type' => 'File'
        ]);
        // 判断用户信息
        $this->order = UserTiMoneyOrder::where('order_no',$order_no)->find();
        $this->user = UserModel::get($this->order['user_id']);
        // 判断订单信息
        if($this->order['status'] != 1) {
            return false;
        }
        if($this->order['money'] < 1) {
            return false;
        }
        if($this->order['money'] > $this->user['money']) {
            return false;
        }
        $params["mch_appid"]        = config('wx.app_id'); //公众账号appid 或者开放平台 appid
        $params["mchid"]            = config('wx.wechat_user_id'); //商户号 微信支付平台账号
        $params["nonce_str"]        = self::createNonceStr(32); //随机字符串
        $params["partner_trade_no"] = $order_no;//商户订单号
        $params["amount"]           = $this->order['money']*100; //金额 单位为分 1元是100
        $params["desc"]             = $this->order['product_name']; //企业付款描述
        $params["openid"]           = $this->user['openid']; //用户openid
        $params["check_name"]       = 'NO_CHECK'; //不检验用户姓名
        $params['spbill_create_ip'] = '124.71.235.83'; //服务器IP
        $str =  'amount='.$params["amount"].'&check_name='.$params["check_name"].'&desc='.$params["desc"].
            '&mch_appid='.$params["mch_appid"].
            '&mchid='.$params["mchid"].
            '&nonce_str='.$params["nonce_str"].
            '&openid='.$params["openid"].'&partner_trade_no='.
            $params["partner_trade_no"].'&spbill_create_ip='.$params['spbill_create_ip'].'&key=74fadeef21b690e249944036a59da3b5';
        $sign = strtoupper(md5($str));
        $params["sign"] = $sign;//签名
        $xml = self::arrayToXml($params);
        $res = self::curl_post_ssl("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers", $xml);
        $result = self::xmlToArray($res);
        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            UserTiMoneyOrder::where('id',$this->order['id'])->update([
                'pay_msg' => json_encode($result),
                'status' => 2,
                'ti_time' => time(),
            ]);
            // 判断用户类型
            if($this->user['type'] == 1) {
                UserModel::where('id',$this->user['id'])->setDec('money',$this->order['money']);
                UserMoneyModel::create([
                    'user_id' => $this->user['id'],
                    'type' => 2,
                    'user_type' => 1,
                    'status' => 3,
                    'money' => $this->order['money'],
                    'user_money' => $this->user['money']
                ]);
            }elseif($this->user['type'] == 2 || $this->user['type'] == 3 || $this->user['type'] == 4 || $this->user['type'] == 7 || $this->user['type'] == 8) {
                $storeUser = StoreUserModel::where('user_id',$this->user['id'])->find();
                UserModel::where('id',$this->user['id'])->setDec('money',$this->order['money']);
                UserMoneyModel::create([
                    'user_id' => $this->user['id'],
                    'type' => 2,
                    'user_type' => 2,
                    'status' => 3,
                    'store_user_id' => $storeUser['id'],
                    'money' => $this->order['money'],
                    'user_money' => $this->user['money']
                ]);
            } elseif($this->user['type'] == 5 || $this->user['type'] == 6 ) {
                $teamUser = TeamUserModel::where('user_id',$this->user['id'])->find();
                UserModel::where('id',$this->user['id'])->setDec('money',$this->order['money']);
                UserMoneyModel::create([
                    'user_id' => $this->user['id'],
                    'type' => 2,
                    'user_type' => 3,
                    'status' => 3,
                    'team_user_id' => $teamUser['id'],
                    'money' => $this->order['money'],
                    'user_money' => $this->user['money']
                ]);
            }
            Log::write('提现返回结果:'.json_encode($result),'info');
            return true;
        } else{
            Log::write('提现返回结果:'.json_encode($result),'info');
            UserTiMoneyOrder::where('id',$this->order['id'])->update([
                'pay_msg' => json_encode($result),
                'status' => 3
            ]);
            return false;
        }
    }

    /**
     * 发送post请求
     *
     */
    private static function curl_post_ssl($url, $vars, $second=30,$aHeader=array()){
        $ch = curl_init();
        //超时时间
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        //引用pem文件
        curl_setopt($ch,CURLOPT_SSLCERT,"/www/wwwroot/digcusmark.com/shuzi-cms/extend/cert/apiclient_cert.pem");
        curl_setopt($ch,CURLOPT_SSLKEY,"/www/wwwroot/digcusmark.com/shuzi-cms/extend/cert/apiclient_key.pem");
        if( count($aHeader) >= 1 ){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }
        curl_setopt($ch,CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
        $data = curl_exec($ch);
        if($data){
            curl_close($ch);
            return $data;
        }else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }

    /**
     * 数组转xml
     *
     */
    private static function arrayToXml($arr) {
        $xml = "<xml>";
        foreach ($arr as $key => $val){
            if (is_numeric($val)){
                $xml .= "<".$key.">".$val."</".$key.">";
            }else{
                $xml .= "<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    /**
     * 将XML转为array
     *
     */
    private static function xmlToArray($xml){
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }

    /**
     * 获取随机字符串
     */
    private static function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
}